package event

import (
	"api/app/tools/services"
	"api/app/wms/auto/v1/mc"
	"api/app/wms/conf"
	"api/app/wms/models"
	service "api/app/wms/services"
	"context"
	"gitee.com/dreamwood/ez"
)

func init() {
	ez.ListenJoin(mc.InLogEventAfterCreate, func(v interface{}, ctx context.Context) {
		md, ok := v.(*models.InLog)
		if ok {
			if md.NumLeft == 0 && md.NumIn > 0 {
				md.NumLeft = md.NumIn
			}
			md.Type = new(models.IOType)
			md.Type.Id = md.TypeId
			md.Type.Read()
			//如果不填单号就自动创建
			if md.Sn == "" {
				//创建批次号
				sn := services.CreateSnByString("StoreInSn", "[YY][MM][DD][DMAX[3]]", 1)
				md.Sn = sn[len("StoreInSn:"):]
			}
			//如果不填批次号就自动创建
			if md.BatchCode == "" {
				//创建批次号
				sn := services.CreateSnByString("StoreInBatch", "[YY][MM][DD][DMAX[3]]", 1)
				md.BatchCode = sn[len("StoreInBatch:"):]
			}
			//如果不填堆号就自动创建
			if md.HeapCode == "" {
				//创建批次号
				sn := services.CreateSnByString("StoreInHeap", "[YY][MM][DD][DMAX[3]]", 1)
				md.HeapCode = sn[len("StoreInHeap:"):]
			}
			md.Save(false)
			//更更新产品的库存
			md.Item = new(models.ItemSku)
			md.Item.Id = md.ItemId
			md.Item.Read()
			service.UpdateItemStorage(md.Item)
			service.CreateChangeLog(md.ItemId, conf.ChangeLogIn)
		}
	})
	ez.ListenJoin(mc.InLogEventAfterUpdate, func(v interface{}, ctx context.Context) {
		md, ok := v.(*models.InLog)
		if ok {
			md.Item = new(models.ItemSku)
			md.Item.Id = md.ItemId
			md.Item.Read()
			service.UpdateItemStorage(md.Item)
			service.CreateChangeLog(md.ItemId, conf.ChangeLogIn)
		}
	})

}
